/***************************operaupdater.cpp*******************************/
/*****************************************************************************/
/*******************Browsers Daily Build Updater************************/
/************Copyright (C) 2010-2011  Gianluigi Biancucci*************/
/*****************************************************************************/
/*****This is free software, and you are welcome to redistribute it****/
/*****and / or modify underthe terms of GPLV2 License.**************/
/*****This program comes with ABSOLUTELY NO WARRANTY*****/
/*****************************************************************************/

#include "OperaUpdater.h"
#include "singletondownloader.h"
#include "iostream"
#include "QFile"
#include <QIcon>
#include <QLabel>
#include <QDir>
#include <QProcess>
#include <QStringList>
#include "operaupdater.h"
#include "QVariant"
#include "paths.h"
#include "winfunc.h"

OperaUpdater::OperaUpdater(QString arch, QString installPath)

{


    downloader = SingletonDownloader::getInstance();
    QDir dir;
    dir = QDir();
    if(!dir.exists(OPERASETPATH+"/"))dir.mkdir(OPERASETPATH+"/");
    _32="win32";
    currPath.setPath(installPath);
   this->setArch(arch);
    BName = "Opera";
    lastError ="No Error";

}

void OperaUpdater::setArch(QString arch){
    //Forced to 32 bit version because there are no 64 bit version of Opera.(For further use)
    currOsType=_32;

}


bool OperaUpdater::downloadLatest(QString * exePath){
    QByteArray  resBA;
    downloader->syncGet("http://my.opera.com/desktopteam/blog/",&resBA);
        QString res(resBA);
         QString version=this->getContentBetween(res,"http://snapshot.opera.com/windows/",".exe");


    QByteArray opera;
    if( downloader->syncGet("http://snapshot.opera.com/windows/"+version+".exe",&opera)){
        QFile* operaFile = new QFile(OPERASETPATH+"/opera_"+version.remove(0,version.length()-13)+".exe");
       operaFile->open(QIODevice::WriteOnly);
       operaFile->write(opera);
       operaFile->close();
        delete operaFile;
        *exePath=OPERASETPATH+"/opera_"+version+".exe";
        return true;
    } else {
        lastError ="Undefined error when downloading Opera installer.\nCheck your connection settings and try again.";
        return false;

    }
}




bool OperaUpdater::getLatestVersion(QString * lastVer){
    //http://snapshot.opera.com/windows/partytime_11.00-1136/Opera_1100_1136_en.exe

    QByteArray  resBA;
    if(downloader->syncGet("http://my.opera.com/desktopteam/blog/",&resBA)){
        QString res(resBA);
         QString verNum=this->getContentBetween(res,"http://snapshot.opera.com/windows/",".exe");
        if((verNum).isEmpty()){lastError="Cannot parse correctly opera download link";return false;}
         int last = verNum.lastIndexOf("_");
         verNum.remove(last,verNum.length());
         verNum.remove(0,verNum.length()-4);
       qDebug(verNum.toStdString().c_str());
         *lastVer=verNum;
        return true;
    }
    else{
        lastError ="Undefined error when checking the latest version of Opera.\nCheck your connection settings and try again.";
        return false;
    }

}

bool OperaUpdater::getInstalledVersion(QString * installedVer){
    QString exePath="";

    if(currPath.exists("opera.exe")){
        exePath=currPath.path()+"/opera.exe";
    }else{
        lastError="Cannot detect Opera version. Maybe corrupted installation or wrong path. Check settings.";
        return false;
    }

    WORD a,b,c,d;
    GetAppVersion(exePath.toStdWString().c_str(),&a,&b,&c,&d);
   // QVariant e=a;
   // QVariant f=b;
    QVariant g=c;
   // QVariant h=d;

    //QString versNum=e.toString()+"."+f.toString()+"."+g.toString()+"."+h.toString();
    QString versNum=g.toString();
    if(!versNum.isEmpty()){
        *installedVer=versNum;

        return true;}
    else{
        lastError="Cannot retrieve correct Opera version. Sorry.";
        return false;
    }
}

bool OperaUpdater::install(QString exePath){

    QString extract = "7z.exe x ";
    extract+=exePath;
    extract+=" -o";
    extract+=OPERASETPATH+"/temp/ ";
    extract.replace("/","\\");

    qDebug(extract.toStdString().c_str());
    system(extract.toStdString().c_str());

    //delete current opera install folder for a new fresh install (user data obviously ramains)
  /*  QString delCmd = "rmdir \""+currPath.path()+"/\"";
    delCmd.replace("/","\\");
    delCmd+=" /S /Q";
    qDebug(delCmd.toStdString().c_str());
    system(delCmd.toStdString().c_str());*/

    //copy the new opera version in the install path
    QString copyCmd = "xcopy "+OPERASETPATH+"/temp/* \""+currPath.path()+"\"";
    copyCmd.replace("/","\\");
    copyCmd+=" /E /H /I /K /Y";
    qDebug(copyCmd.toStdString().c_str());
    system(copyCmd.toStdString().c_str());

    //delete the temporary files
   QString delCmd = "rmdir "+OPERASETPATH+"/temp";
    delCmd.replace("/","\\");
    delCmd+=" /S /Q";
    qDebug(delCmd.toStdString().c_str());
    system(delCmd.toStdString().c_str());

    QMessageBox msg;
    msg.setWindowTitle("Update Ok");
    msg.setIcon(QMessageBox::Information);
    msg.setText("Opera succesfully updated.\n("+currPath.path()+")");
    msg.exec();

    return true;
}


QString OperaUpdater::getContentBetween(QString source, QString startStr, QString endStr){


    int start = source.indexOf(startStr);
    if(start != -1){
        source.remove(0,start+startStr.length());
        int end = source.indexOf(endStr);
        if (end != -1){
            source.remove(end,source.length()-end);
            return source;
        }else return "";

    }else return "";
    }

bool OperaUpdater::checkInstallPath(){
    if(currPath.exists("opera.exe"))return true;
    else return false;
}


QString OperaUpdater::getBrowserName(){

    return BName;

}

QString OperaUpdater::getLastError(){

    return lastError;

}
